import { defineStore } from 'pinia'
import { ref } from 'vue'
import type {DragResult} from "smooth-dnd";

export const useSmoothDnd01a = defineStore('smoothDnd01a', () => {
  const items = ref(['item1', 'item2', 'item3'])

  /**
   * 末尾追加
   * @param item
   */
  function addItems(item: any) {
    items.value.push(item);
  }

  /**
   * 整体替换
   * @param items
   */
  function replaceAll(newItems: []){
    items.value = [...newItems]
  }

  const applyDrag = <T extends any[]>(arr: T, dragResult: DragResult)=>{
    const result = [...arr];
    const {addedIndex, removedIndex, payload} = dragResult;
    // 这是添加，也就是从外面拖入
    if(addedIndex!==null&&removedIndex===null){
      result.splice(addedIndex, 0, payload);
    }
    // 这是移动，也就是在当前容器内拖动改变顺序
    else if(addedIndex!==null&&removedIndex!==null){
      return  arrayMove(items.value, removedIndex, addedIndex);
    }
    return result;
  }
  return { items, addItems, replaceAll, applyDrag}
})
function arrayMove<T>(array: T[], from: number, to: number): T[] {
  const newArray = array.slice()
  newArray.splice(to < 0 ? newArray.length + to : to, 0, newArray.splice(from, 1)[0])

  return newArray
}
